<template>
    <div class="upload-wrap">
        <el-upload ref="upload" 
        :class="showType == 'avatar' ? 'avatar-uploader' : ''" 
        :action="uploadUrl" 
        :data="options" 
        :accept="acceptTypeInner" 
        :list-type="showType == 'avatar' ? '' : showType" 
        :limit="showType == 'avatar' ? 999 : limit" 
        :show-file-list="showType == 'avatar' ? false : showFileList" 
        :on-exceed="uploadExceed" :before-upload="beforeUpload" 
        :file-list="fileList" 
        :on-progress = "uploadProgress" 
        :on-success="arg => uploadSuccess(arg, options.key)">
            <template v-if="showType == 'avatar'">
                <div v-if="imageUrl">
                    <img :src="imageUrl" class="avatar">
                    <el-progress v-if="imageUrl.indexOf('blob:') > -1" type="circle" :percentage="uploadPercent"></el-progress>
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </template>
            <template v-else-if="showType == 'text'">
                <el-button size="small" type="primary">点击上传</el-button>
                <slot></slot>
                <div slot="tip" class="el-upload__tip"><slot name="tip"></slot></div>
            </template>
            <template v-else>
                <i class="el-icon-plus"></i>
            </template>
        </el-upload>
    </div>
</template>
<script>
    import { Base64 } from 'js-base64';
    import { getRandomCharacters } from '@/assets/util.js'
    // import { CryptoJS } from 'crypto-js';
    import '@/assets/crypto/crypto/crypto.js'
    import '@/assets/crypto/hmac/hmac.js'
    import '@/assets/crypto/sha1/sha1.js'
    const accessid = 'LTAIAA5oGypvXDOP';
    const accesskey = 'qwWx2NZGHEVGurA3go9rBlQSGrSfza';
    const host = 'http://penguin-courses.oss-cn-shanghai.aliyuncs.com';
    const policyText = {
        "expiration": "2030-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };
    const policyBase64 = Base64.encode(JSON.stringify(policyText))
    const message = policyBase64
    // const bytes = CryptoJS.HmacSHA1(message, accesskey)
    var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
    var signature = Crypto.util.bytesToBase64(bytes);

    export default {
        name: 'Upload',
        props: {
            showType: String,
            acceptType: String,
            showFileList: Boolean,
            limit: Number,
            size: Number,
            fileList: {
                type: Array,
                default: () => []
            },
            exist: String
        },
        watch: {
            'exist': function(v){
                this.imageUrl = v
            }
        },
        computed: {
            'acceptTypeInner': function() {
                return this.acceptType == 'image' ? 'image/*' : 'video/mp4, audio/mp3'
            }
        },
        data() {
            return {
                uploadUrl: host,
                imageUrl: '',
                uploadPercent: 0,
                // acceptType: 'image/*, video/*, audio/*',
                options: {
                    'key': '',
                    'policy': policyBase64,
                    'OSSAccessKeyId': accessid,
                    'success_action_status': '200', //让服务端返回200，不设置则默认返回204
                    'signature': signature,
                    // 'x-oss-security-token': token
                }
            }
        },
        mounted(){
            this.imageUrl = this.fileList.length > 0 ? this.fileList[0].url : ''
        },
        methods: {
            beforeUpload(file) {
                if( this.size && (file.size / 1024) > this.size) {
                    this.$message.error('请上传' + this.size + 'kb以下的图片')
                    return false
                }
                let nameArg = file.name.split('.'),
                    fileName = nameArg[0],
                    fileExt = nameArg.length > 1 ? ('.' + nameArg[nameArg.length - 1]) : '',
                    key = fileName + '____' + getRandomCharacters(8) + fileExt;
                this.options.key = this.acceptType + '/' + key
                this.options.Filename = key
                this.uploadPercent = 0
                if(this.acceptType === 'image'){
                    this.imageUrl = URL.createObjectURL(file);
                }
                // return false
            },
            uploadProgress(event, file, fileLis){
                this.uploadPercent = ~~event.percent
            },
            uploadSuccess(file, key) {
                this.imageUrl = host + '/' + key
                this.$emit('upload-change', host + '/' + key)
                this.$refs.upload.clearFiles()

                // console.log(file, key)
            },
            uploadExceed(files, fileList) {
                // console.log(file, fileList)
                // let newList = fileList.splice(fileList.length-1 , 1 , files[0])
                this.$message.error('同时只能上传' + this.limit + '个文件/图片')
            }
        }
    }
</script>

<style scoped lang="scss">
    .avatar-uploader /deep/ {
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            &:hover {
                border-color: var(--primary);
            }
        }
        .el-progress--circle{
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -63px;
            margin-top: -63px;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    }
</style>